<!--供应商管理-->
<template>
    <el-form :model="supplierform" ref="supplierRef" :inline="true" style="text-align: left;">
        <el-form-item label="供应商:" prop="sup_code">
            <el-input placeholder="请输入供应商名称/编号" v-model="supplierform.sup_code" style="width:180px"></el-input>
        </el-form-item>
        <el-form-item label="状态:" prop="sup_status">
            <el-select placeholder="请选择" v-model="supplierform.sup_status" style="width:180px">
                <el-option label="启用" :value="0"></el-option>
                <el-option label="停用" :value="1"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="所属行业:" prop="sup_industry">
            <el-select v-model="supplierform.sup_industry" placeholder="请选择" style="width:180px">
                <el-option
                    v-for="item in Industrydata"
                    :key="item.dict_code"
                    :label="item.dict_label"
                    :value="item.dict_label"
                />
            </el-select>
        </el-form-item>
        <el-form-item label="进货负责人:" prop="sup_userName">
            <el-select v-model="supplierform.sup_userName" placeholder="请选择" style="width:180px">
                <el-option
                    v-for="item in Userdata"
                    :key="item.user_id"
                    :label="item.user_name"
                    :value="item.user_name"
                />
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button @click="Reset">重置</el-button>
            <el-button type="success" @click="Search()">查询</el-button>
            <el-button @click="showAdvancedPanel">高级查询</el-button>
        </el-form-item>
    </el-form>
    <div style="text-align: left;">
        <el-button type="success" @click="jump()">新增</el-button>
        <el-button @click="DeleteAll">删除</el-button>
        <el-button @click="exportData">导出</el-button>
        <el-button @click="Import">导入</el-button>
    </div>
    <!-- 外层容器，允许水平滚动 -->
    <div class="table-container" style="overflow-x: auto; margin-top: 20px;">
        <!-- 设置表格高度以实现垂直滚动 -->
        <el-table :data="supplierdata" style="width: 100%;" ref="tableRef" @selection-change="SelectChange">
            <!-- 左侧固定列 -->
            <el-table-column fixed type="selection"></el-table-column>
            <el-table-column type="index" label="序号" width="70" fixed></el-table-column>
            <el-table-column fixed label="供应商编码" width="150">
                <template #default="scope">
                    <span class="clickable-cell" style="color: green;cursor: pointer;" @click="Jumptodetail(scope.row.sup_id,scope.row.sup_code)">{{ scope.row.sup_code }}</span>
                </template>
            </el-table-column>
            <el-table-column fixed prop="sup_name" label="供应商" width="150px"></el-table-column>

            <!-- 中间可滚动列，为每列设置明确宽度 -->
            <el-table-column prop="sup_industry" label="所属行业" width="120"></el-table-column>
            <el-table-column prop="sup_type" label="供应商分类" width="120"></el-table-column>
            <el-table-column prop="sup_linkman" label="联系人" width="100"></el-table-column>
            <el-table-column prop="sup_linkphone" label="联系电话" width="130"></el-table-column>
            <el-table-column prop="sup_email" label="电子邮箱" width="150"></el-table-column>
            <el-table-column prop="sup_depName" label="进货部门" width="120"></el-table-column>
            <el-table-column prop="sup_userName" label="进货负责人" width="120"></el-table-column>
            <el-table-column prop="sup_status" label="状态" width="80">
            <template #default="scope">
                {{ scope.row.sup_status === 0 ? '启用' : '停用' }}
            </template>
            </el-table-column>
            <el-table-column prop="sup_address" label="供应商地址" width="200"></el-table-column>
            <el-table-column prop="sup_accountName" label="账户名称" width="200"></el-table-column>
            <el-table-column prop="sup_taxpayerNum" label="纳税人识别号" width="200"></el-table-column>
            <el-table-column prop="sup_bankAccount" label="银行账户" width="200"></el-table-column>
            <el-table-column prop="sup_openBank" label="开户银行" width="200"></el-table-column>
            <el-table-column prop="sup_openBankAddress" label="开户行地址" width="200"></el-table-column>
            <el-table-column prop="create_time" label="操作时间" width="200"></el-table-column>
            
            <!-- 右侧固定列 -->
            <el-table-column fixed="right" label="操作" width="155px">
                <template #default="scope">
                    <el-button type="success" text="编辑" @click="jump(scope.row.sup_id)">编辑</el-button>
                    <el-button type="danger" text="删除" @click="deleteSupplier(scope.row.sup_id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <!-- 页码 -->
    <!-- 修改分页组件 layout 属性 -->
    <el-pagination
        :page-size="10"
        :pager-count="11"
        layout="prev, pager, next, jumper"
        :total="rows"
        @current-change="handlePageChange"
        style="float:right;margin-top:20px;">
    </el-pagination>
    <!-- 遮罩层 -->
    <div class="mask" ref="mask" @click="hideAdvancedPanel"></div>
        
    <!-- 高级查询面板 -->
    <div class="advanced-panel" ref="advancedPanel">
        <div class="panel-header">
            <div class="panel-title">供应商高级查询</div>
            <button class="close-btn" @click="hideAdvancedPanel">×</button>
        </div>
        <div class="panel-body">
            <div>
                <div>供应商编码</div>
                <div><input type="text" placeholder="请输入" v-model="supplierformsenior.sup_code"></div>
            </div>
            <div>
                <div>供应商名称</div>
                <div><input type="text" placeholder="请输入" v-model="supplierformsenior.sup_name"></div>
            </div>
            <div>
                <div>所属行业</div>
                <el-select v-model="supplierformsenior.sup_industry" placeholder="请选择" style="width:100%">
                    <el-option
                        v-for="item in Industrydata"
                        :key="item.dict_code"
                        :label="item.dict_label"
                        :value="item.dict_label"
                    />
                </el-select>
            </div>
            <div>
                <div>供应商分类</div>
                <el-select v-model="supplierformsenior.sup_type" placeholder="请选择" style="width:100%">
                    <el-option
                        v-for="item in Classifydata"
                        :key="item.dict_code"
                        :label="item.dict_label"
                        :value="item.dict_label"
                    />
                </el-select>
            </div>
            <div>
                <div>联系人</div>
                <div><input type="text" placeholder="请输入" v-model="supplierformsenior.sup_linkphone"></div>
            </div>
            <div>
                <div>联系电话</div>
                <div><input type="text" placeholder="请输入" v-model="supplierformsenior.sup_email"></div>
            </div>
            <div>
                <div>电子邮箱</div>
                <div><input type="text" placeholder="请输入" v-model="supplierformsenior.sup_email"></div>
            </div>
            <div>
                <div>进货部门</div>
                <el-select v-model="supplierformsenior.sup_depName" placeholder="请选择" style="width:100%">
                    <el-option
                        v-for="item in Departmentdata"
                        :key="item.department_id"
                        :label="item.department_name"
                        :value="item.department_name"
                    />
                </el-select>
            </div>
            <div>
                <div>进货负责人</div>
                <el-select v-model="supplierformsenior.sup_userName" placeholder="请选择" style="width:100%">
                    <el-option
                        v-for="item in Userdata"
                        :key="item.user_id"
                        :label="item.user_name"
                        :value="item.user_name"
                    />
                </el-select>
            </div>
            <div>
                <div>状态</div>
                <el-select v-model="supplierformsenior.sup_status" placeholder="请选择">
                    <el-option label="启用" :value="0"></el-option>
                    <el-option label="停用" :value="1"></el-option>
                </el-select>
            </div>
            <div>
                <div>供应商地址</div>
                <div><input type="text" placeholder="请输入" v-model="supplierformsenior.sup_addresscode"></div>
            </div>
            <div>
                <div>账户名称</div>
                <div><input type="text" placeholder="请输入" v-model="supplierformsenior.sup_accountName"></div>
            </div>
            <div>
                <div>纳税人识别号</div>
                <div><input type="text" placeholder="请输入" v-model="supplierformsenior.sup_taxpayerNum"></div>
            </div>
            <div>
                <div>银行账户</div>
                <div><input type="text" placeholder="请输入" v-model="supplierformsenior.sup_bankAccount"></div>
            </div>
            <div>
                <div>开户银行</div>
                <div><input type="text" placeholder="请输入" v-model="supplierformsenior.sup_openBank"></div>
            </div>
            <div>
                <div>操作人</div>
                <el-select v-model="supplierformsenior.create_name" placeholder="请选择" style="width:100%">
                    <el-option
                        v-for="item in Userdata"
                        :key="item.user_id"
                        :label="item.user_name"
                        :value="item.user_name"
                    />
                </el-select>
            </div>
            <div>
                <div>操作时间</div>
                <div>
                    <el-date-picker
                        v-model="dateRange"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"
                        style="width:100%"
                        @change="handleDateChange"
                    />
                </div>
            </div>
        </div>
        <div class="panel-footer">
            <el-button class="action-btn" @click="resetSeniorForm">重置</el-button>
            <el-button class="action-btn" @click="hideAdvancedPanel">关闭</el-button>
            <el-button type="success" class="action-btn btn-query" @click="GetSeniorSupplier()">查询</el-button>
        </div>
    </div>
</template>

<script>
import { useRouter } from 'vue-router'
import {ref,reactive,onMounted,nextTick} from 'vue';
import http from '../auth/index';
import { ElMessage,ElMessageBox } from 'element-plus'; //提示信息
import * as XLSX from 'xlsx';
export default {
setup()
    {
        const router = useRouter();
        //表单
        const supplierRef = ref(null)

        // 日期范围
        const dateRange = ref([]);
        // 开始和结束时间
        const startTime = ref('');
        const endTime = ref('');

        // 处理日期变化
        function handleDateChange(dates) {
            if (dates && dates.length === 2) {
                startTime.value = dates[0] + ' 00:00:00';
                endTime.value = dates[1] + ' 23:59:59';
            } else {
                startTime.value = '';
                endTime.value = '';
            }
        }


        //简单查询表单
        const supplierform = reactive({
            sup_code:"",
            sup_status:null,
            sup_industry:"",
            sup_userName:""
        })

        //高级查询表单
        const supplierformsenior = reactive({
            sup_code:"",
            sup_name:"",
            sup_industry:"",
            sup_type:"",
            sup_linkman:"",
            sup_linkphone:"",
            sup_email:"",
            sup_depName: "",
            sup_userName: "",
            sup_status:null,
            sup_address:"",
            sup_accountName:"",
            sup_taxpayerNum:"",
            sup_bankAccount:"",
            sup_openBank:"",
            create_name:"",
        })

        function GetSeniorSupplier() {
            http.get("/Supplier/GetSeniorSupplier", {
                params: {
                    CurrentPage: currentPage.value,
                    sup_code:supplierformsenior.sup_code,//编号
                    sup_name:supplierformsenior.sup_name,//姓名
                    sup_industry:supplierformsenior.sup_industry,//所属行业
                    sup_type:supplierformsenior.sup_type,//供应商分类
                    sup_linkman:supplierformsenior.sup_linkman,//联系人
                    sup_linkphone:supplierformsenior.sup_linkphone,//联系电话
                    sup_email:supplierformsenior.sup_email,//电子邮箱
                    sup_depName: supplierformsenior.sup_depName, // 使用部门名称
                    sup_userName: supplierformsenior.sup_userName, // 使用负责人姓名
                    sup_status:supplierformsenior.sup_status,//状态
                    sup_address:supplierformsenior.sup_address,//供应商地址
                    sup_accountName:supplierformsenior.sup_accountName,//账户名称
                    sup_taxpayerNum:supplierformsenior.sup_taxpayerNum,//纳税人识别号
                    sup_bankAccount:supplierformsenior.sup_bankAccount,//银行账户
                    sup_openBank:supplierformsenior.sup_openBank,//开户银行
                    create_name:supplierformsenior.create_name,//创建人
                    startTime: startTime.value, // 开始时间
                    endTime: endTime.value     // 结束时间
                }
            }).then(res => {
                console.log("API数据:", res.data); // 调试用
                
                // 正确解析分页数据
                const fenye = res.data;
                if (!fenye || !fenye.list) {
                ElMessage.warning('没有相关数据.');
                return;
                }

                // 更新总数据量（总记录数）
                rows.value = fenye.rows || 0;

                // 处理当前页数据
                const Data = fenye.list.map(item => ({
                ...item,
                create_time: formatDateTime(new Date(item.create_time)),
                }));

                // 赋值给表格数据
                supplierdata.value = Data;
                hideAdvancedPanel()

                // 如果当前页数据为空且不是第一页，自动跳转到上一页
                if (Data.length === 0 && currentPage.value > 1) {
                handlePageChange(currentPage.value - 1);
                }
            }).catch(err => {
                console.log(err);
                ElMessage.error('数据加载失败');
            });
        }
        //日期格式
        const dateFormat='YYYY-MM-DD HH:mm:ss';

        //日期转换格式
        function formatDateTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

         //表格数据
         const supplierdata = ref([]);
        //总数据量
        const rows = ref(0);
        //当前页
        const currentPage = ref(1);

        // 重置方法
        function Reset() {
            if (supplierRef.value) {
                supplierRef.value.resetFields()
            }
            // 重置所有表单字段
            Object.keys(supplierformsenior).forEach(key => {
                supplierformsenior[key] = '';
            });
            
            // 重置日期范围
            dateRange.value = [];
            startTime.value = '';
            endTime.value = '';
            All();
        }

        //刷新
        function Search(){
            All(); // 用空条件搜索所有数据
        }

        //查询数据
        function All() {
            http.get("/Supplier/GetSupplier", {
                params: {
                    sup_code: supplierform.sup_code,
                    sup_name: supplierform.sup_code, // 这里可能需要确认参数名是否正确
                    sup_status: supplierform.sup_status,
                    sup_industry: supplierform.sup_industry,
                    sup_userName: supplierform.sup_userName,
                    CurrentPage: currentPage.value
                }
            }).then(res => {
                console.log("API数据:", res.data); // 调试用
                
                // 正确解析分页数据
                const fenye = res.data;
                if (!fenye || !fenye.list) {
                ElMessage.warning('没有相关数据.');
                return;
                }

                // 更新总数据量（总记录数）
                rows.value = fenye.rows || 0;

                // 处理当前页数据
                const Data = fenye.list.map(item => ({
                ...item,
                create_time: formatDateTime(new Date(item.create_time)),
                }));

                // 赋值给表格数据
                supplierdata.value = Data;

                // 如果当前页数据为空且不是第一页，自动跳转到上一页
                if (Data.length === 0 && currentPage.value > 1) {
                    handlePageChange(currentPage.value - 1);
                }
            }).catch(err => {
                console.log(err);
                ElMessage.error('数据加载失败');
            });
        }

        //改变页数
        function handlePageChange(page) {
            currentPage.value = page
            All();
        }

        const Departmentdata = ref([]);
        const Userdata = ref([]);
        const Industrydata = ref([]);
        const Classifydata = ref([]);

        // 查询部门数据
        function GetDepartment() {
            http.get("/Supplier/GetDepartment", {
                params: {
                    Department_id: name
                }
            }).then(res => {
                console.log("API数据:", res.data); // 调试用
                Departmentdata.value = res.data; // 将查询结果赋值给 Departmentdata
            }).catch(err => {
                console.log(err);
                ElMessage.error('数据加载失败');
            });
        }

        // 查询用户数据
        function GetUser() {
            http.get("/Supplier/GetUser", {
                params: {
                    Department_id: name
                }
            }).then(res => {
                console.log("API数据:", res.data); // 调试用
                Userdata.value = res.data; // 将查询结果赋值给 Userdata
            }).catch(err => {
                console.log(err);
                ElMessage.error('数据加载失败');
            });
        }

        // 查询字典数据
        function GetDictData(zd) {
            http.get("/Supplier/GetDictData", {
                params: {
                    dict_id: zd
                }
            }).then(res => {
                if (zd === 10) {
                    Classifydata.value = res.data; // 将查询结果赋值给 Classifydata
                    console.log("行业数据:", Classifydata.value); // 调试用
                } else if (zd === 12) {
                    Industrydata.value = res.data; // 将查询结果赋值给 Industrydata
                    console.log("分类:", Industrydata.value); // 调试用
                }
            }).catch(err => {
                console.log(err);
                ElMessage.error('数据加载失败');
            });
        }

        //挂载
        onMounted(() => {
            All();
            GetDepartment()//部门
            GetUser()//用户
            GetDictData(10)//行业
            GetDictData(12)//分类
        });

        // DOM元素引用
        const mask = ref(null);
        const advancedPanel = ref(null);
        
        // 显示高级面板
        function showAdvancedPanel(){
            mask.value.style.display = 'block';
            setTimeout(() => {
                mask.value.style.opacity = '1';
                advancedPanel.value.style.right = '0';
            }, 10);
        };
        
        // 隐藏高级面板
        function hideAdvancedPanel(){
            advancedPanel.value.style.right = '-400px';
            mask.value.style.opacity = '0';
            setTimeout(() => {
                mask.value.style.display = 'none';
            }, 300);
        };

        function jump(id = null) {
            // 如果传入 ID，表示编辑模式，否则为新增模式
            if (id) {
                router.push({ path: 'suppliernew', query: { id: id } });
            } else {
                router.push('suppliernew');
            }
        }

        function flushed(){
            All();
        }

        function exportData() {
            if (selectdata.value.length === 0) {
                ElMessage.warning('请选择要导出的数据');
                return;
            }
    
            // 创建工作簿
            const wb = XLSX.utils.book_new();
            const excelData = selectdata.value.map((row) => ({
                '供应商编码': row.sup_code,
                '供应商': row.sup_name,
                '所属行业':row.sup_industry,
                '供应商分类': row.sup_type,
                '联系人': row.sup_linkman,
                '联系电话': row.sup_linkphone,
                '电子邮箱': row.sup_email,
                '进货部门id':row.sup_depId,
                '进货部门': row.sup_depName,
                '进货负责人id':row.sup_userId,
                '进货负责人': row.sup_userName,
                '备注':row.remark,
                '状态': row.sup_status,
                '供应商地址': row.sup_address,
                '账户名称': row.sup_accountName,
                '纳税人识别号': row.sup_taxpayerNum,
                '银行账户': row.sup_bankAccount,
                '开户银行': row.sup_openBank,
                '开户行地址': row.sup_openBankAddress,
                '创建人':row.create_name,
                '操作时间': row.create_time
            }));
            // 创建工作表
            const ws = XLSX.utils.json_to_sheet (excelData);
            // 添加到工作簿
            XLSX.utils.book_append_sheet(wb, ws, "供应商数据");
            // 导出并下载
            XLSX.writeFile(wb, `供应商数据${new Date().toLocaleDateString()}.xlsx`);
        }

        function Import() {
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = '.xlsx, .xls';
            input.onchange = async (event) => {
                const file = event.target.files[0];
                if (file) {
                    try {
                        // 使用 FormData 上传文件
                        const formData = new FormData();
                        formData.append('file', file);

                        // 直接调用后端的 ImportSupplier 接口
                        const result = await http.post("/Supplier/ImportSupplier", formData, {
                            headers: {
                                'Content-Type': 'multipart/form-data' // Axios 通常会自动设置，但明确指定更安全
                            }
                        });

                        // 处理后端返回的导入结果
                        if (result.status === 200) {
                            const data = result.data;
                            const successCount = data.successCount || 0;
                            const errorCount = data.errorCount || 0;
                            const errors = data.errors || [];

                            let message = `导入完成。成功: ${successCount} 条`;
                            if (errorCount > 0) {
                                message += `, 失败: ${errorCount} 条`;
                                if (errors.length > 0) {
                                    // 可以选择显示部分错误信息
                                    const errorSummary = errors.slice(0, 5).join('; '); // 只显示前5个错误
                                    const moreErrors = errors.length > 5 ? `... (还有 ${errors.length - 5} 个错误)` : '';
                                    message += `。错误详情: ${errorSummary}${moreErrors}`;
                                }
                                ElMessage.warning(message);
                            } else {
                                ElMessage.success(message);
                            }
                        } else {
                            ElMessage.error('导入请求失败: ' + (result.data?.message || result.statusText || ''));
                        }

                        // 刷新数据
                        All();
                    } catch (err) {
                        console.error('导入错误:', err);
                        let errorMsg = '导入失败';
                        if (err.response?.data?.message) {
                            errorMsg = `导入失败: ${err.response.data.message}`;
                            // 如果后端返回了详细的错误列表，也可以尝试显示
                            if (err.response.data.errors && Array.isArray(err.response.data.errors) && err.response.data.errors.length > 0) {
                                const errorDetails = err.response.data.errors.slice(0, 3).join('; '); // 显示前几个
                                errorMsg += `。部分错误: ${errorDetails}`;
                            }
                        } else if (err.message) {
                            errorMsg = `导入失败: ${err.message}`;
                        }
                        ElMessage.error(errorMsg);
                    }
                }
            };
            input.click();
        }

        // 删除供应商方法
        function deleteSupplier(id) {
            ElMessageBox.confirm('确定要删除该供应商吗？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                    const res = await http.put('/Supplier/DeleteSupplier?id='+id);
                    // 处理成功响应
                    if (res.data?.code === 1) {
                        ElMessage.success(res.data.message || '删除成功');
                        All(); // 刷新列表
                        return;
                    }else {
                        ElMessage.error('响应格式错误或未知成功状态: ' + (res.data?.message || ''));
                    }
                } catch (err) {
                    console.error("删除供应商请求失败:", err);
                    
                    // 统一错误处理
                    let errorMsg = '删除请求失败';
                    if (err.response?.data?.message) {
                        errorMsg = err.response.data.message;
                    } else if (err.message) {
                        errorMsg = err.message;
                    }
                    
                    // 根据错误类型显示不同提示
                    if (err.response?.data?.code === 0) {
                        ElMessageBox.alert(errorMsg, '删除失败', {
                            type: 'warning',
                            confirmButtonText: '确定'
                        });
                    } else if (err.response?.data?.code === -1) {
                        ElMessage.warning(errorMsg || '供应商不存在或已被删除');
                        All(); // 刷新列表
                    } else {
                        ElMessage.error(errorMsg);
                    }
                }
            }).catch(() => {
                ElMessage.info('已取消删除');
            });
        }

        // 在 setup() 中添加：
        // 重置高级查询表单
        function resetSeniorForm() {
            // 重置所有表单字段
            Object.keys(supplierformsenior).forEach(key => {
                supplierformsenior[key] = '';
            });
            
            // 重置日期范围
            dateRange.value = [];
            startTime.value = '';
            endTime.value = '';
            
            ElMessage.success('高级查询条件已重置');
        }
        
        const tableRef = ref(null); // 添加表格引用
        const selectdata=ref([]);//选中数据
        // 获取选中数据
        function SelectChange(selection) {
            selectdata.value = selection;
        }

        // 批量删除
        function DeleteAll() {
            if (selectdata.value.length === 0) {
                ElMessage.warning('请选择要删除的数据');
                return;
            }
            ElMessageBox.confirm('确定要删除选中的供应商吗？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => { // 改为 async 以便使用 await
                try {
                    let successCount = 0;
                    let failCount = 0;
                    let messages = []; // 存储失败的具体原因

                    // 使用 for...of 循环以便 await 每个请求
                    for (const item of selectdata.value) {
                        try {
                            // 对每个选中的供应商发起删除请求
                            const res = await http.put(`/Supplier/DeleteSupplier?id=${item.sup_id}`);
                            
                            // 处理成功的响应 (HTTP 200)
                            if (res.data && res.data.code === 1) {
                                successCount++;
                            } else {
                                // 理论上不太可能，但如果后端返回了非预期的成功 code
                                failCount++;
                                messages.push(`供应商 ${item.sup_name}: 响应异常 (${res.data?.message || '未知'})`);
                            }
                        } catch (err) {
                            // 处理失败的响应 (HTTP 4xx, 5xx)
                            failCount++;
                            
                            let errorMsg = `请求失败`;
                            if (err.response && err.response.data && err.response.data.message) {
                                errorMsg = err.response.data.message; // 使用后端返回的具体错误信息
                            } else if (err.message) {
                                errorMsg = err.message; // 使用 Axios 的错误信息
                            }
                            
                            messages.push(`供应商 ${item.sup_name}: ${errorMsg}`);
                            console.error(`删除供应商 ${item.sup_name} 失败:`, err);
                        }
                    }

                    // 显示批量删除的最终结果
                    if (failCount > 0) {
                        // *** 修改点: 使用 <br> 标签和 HTML 来实现换行 ***
                        // 将 \n 替换为 <br> 以便在 HTML 中正确换行
                        const combinedMessage = messages.length > 3 ?
                            `${messages.slice(0, 3).join('<br>')}<br>...(还有 ${messages.length - 3} 条错误)` :
                            messages.join('<br>');
                        // *** 修改结束 ***

                        // 检查是否主要是因为引用失败 (可以根据 messages 内容进一步细化)
                        const hasReferenceError = messages.some(msg => msg.includes('引用'));

                        ElMessageBox.alert(combinedMessage, `删除结果 (${successCount} 成功, ${failCount} 失败)`, {
                            type: hasReferenceError ? 'warning' : 'error',
                            confirmButtonText: '确定',
                            // *** 关键修改: 确保 dangerouslyUseHTMLString 为 true 以渲染 HTML ***
                            dangerouslyUseHTMLString: true, // 允许使用 HTML
                            // *** 修改结束 ***
                            customClass: 'scrollable-alert' // 可选：添加自定义类名用于样式调整
                        }).catch(() => {}); // 忽略用户关闭弹窗的潜在错误
                    }
                    
                    // 无论成功与否，都刷新列表和清空选择
                    All(); 
                    tableRef.value.clearSelection(); 
                    
                } catch (err) {
                    // 捕获 for 循环之外的意外错误 (可能性较低)
                    console.error("批量删除过程中发生未预期的错误:", err);
                    ElMessage.error('批量删除过程出错: ' + (err.message || ''));
                }
            }).catch(() => {
                // 用户取消批量删除操作
                ElMessage.info('已取消批量删除');
            });
        }

        function Jumptodetail(id,code) {
            router.push({ path: 'supplierdetail', query: { id: id ,code:code} });
        }

        return{
            supplierform,
            supplierRef,
            supplierformsenior,
            dateFormat,
            Reset,
            Search,
            supplierdata,
            formatDateTime,
            rows,
            handlePageChange,
            showAdvancedPanel,
            hideAdvancedPanel,
            mask,
            advancedPanel,
            jump,
            Jumptodetail,
            exportData,
            deleteSupplier,
            flushed,
            GetSeniorSupplier,
            Departmentdata,
            Userdata,
            Industrydata,
            Classifydata,
            dateRange,
            handleDateChange,
            resetSeniorForm,
            DeleteAll,
            SelectChange,
            tableRef,
            Import
        }
    }
}
</script>

<style scoped>
        .panel-body {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px 20px;
            padding: 15px;
            background: #f9fbfd;
            text-align: left;
            flex: 1;
            overflow-y: auto;
            display: grid;
            grid-template-columns: 1fr 1fr;
        }
        
        .panel-body input {
            width: 100%;
            padding: 6px 10px;  /* 减小高度 */
            border: 1px solid #d1d8e0;
            border-radius: 4px;
            font-size: 14px;
            max-width: calc(100% - 20px); /* 减小宽度 */
        }
        
        .panel-body input:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
        }
        /* === 以下是新增的高级查询面板样式 === */
        .mask {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            display: none;
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        
        .advanced-panel {
            position: fixed;
            top: 0;
            right: -400px;
            width: 400px;
            height: 100%;
            background: white;
            z-index: 1001;
            box-shadow: -5px 0 15px rgba(0, 0, 0, 0.1);
            transition: right 0.3s ease;
            display: flex;
            flex-direction: column;
        }
        
        .panel-header {
            padding: 15px;
            background: #f8f9fa;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .panel-title {
            font-size: 16px;
            font-weight: 600;
            color: #333;
        }
        
        .close-btn {
            background: none;
            border: none;
            font-size: 18px;
            cursor: pointer;
            color: #999;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 6px;
            font-size: 13px;
            color: #555;
            font-weight: 500;
        }
        
        .form-group input, 
        .form-group select {
            width: 100%;
            padding: 8px 10px;
            border: 1px solid #ddd;
            border-radius: 3px;
            font-size: 13px;
        }
        
        .panel-footer {
            padding: 12px 15px;
            background: #f8f9fa;
            border-top: 1px solid #eee;
            display: flex;
            justify-content: flex-end;
            gap: 8px;
        }
</style>